package com.xuecheng.service.impl;

import com.xuecheng.mapper.CourseBaseMapper;
import com.xuecheng.mapper.CourseCategoryMapper;
import com.xuecheng.mapper.CourseMarketMapper;
import com.xuecheng.model.dto.AddCourseDto;
import com.xuecheng.model.dto.CourseBaseInfoDto;
import com.xuecheng.model.dto.CourseCategoryTreeDto;
import com.xuecheng.model.po.CourseBase;
import com.xuecheng.model.po.CourseCategory;
import com.xuecheng.model.po.CourseMarket;
import com.xuecheng.service.CourseCategoryService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 小班哥
 * @version 1.0
 * @date 2023/3/13 10:11
 * @description
 */

@Service
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    private CourseCategoryMapper categoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //查询所有根节点和子节点
        List<CourseCategoryTreeDto> selectTreeNodes = categoryMapper.selectTreeNodes(id);
        //将list转成map，key是节点的ID value就是它自己，目的就是方便从map中获取节点
        // filter(exclude -> !id.equals(exclude.getId())把根节点排除
        //(key1 , key2) -> key2) 如果key重复了已哪一个key为主
        Map<String, CourseCategoryTreeDto> dtoMap =
                selectTreeNodes.stream().filter(exclude -> !id.equals(exclude.getId()))
                        .collect(Collectors.toMap(key -> key.getId(), value -> value , (key1 , key2) -> key2));
        //new 一个List 用于返回最终的数据
        List<CourseCategoryTreeDto> list = new ArrayList<>();
        //从头开始遍历，将子节点放到父节点中
        selectTreeNodes.stream().filter(exclude -> !id.equals(exclude.getId())).forEach(cateDto ->{
            //判断当前节点是否是跟节点，如果是就把它加入list中
            if (id.equals(cateDto.getParentid())){
                list.add(cateDto);
            }
            //拿到父节点
            CourseCategoryTreeDto courseCategoryTreeDto = dtoMap.get(cateDto.getParentid());
            //如果当前节点的父节点是否为空
            if (courseCategoryTreeDto != null){
                //判断父节点的字节点是否为空
                if (courseCategoryTreeDto.getChildrenTreeNodes() == null){
                    //如果为空则new一个空集合给他，避免爆空集合异常
                    courseCategoryTreeDto.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //将子节点放到父节点中
                courseCategoryTreeDto.getChildrenTreeNodes().add(cateDto);
            }
        });
        return list;
    }


}
